package com.css.dzj.zfjg.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 模板下载
 * @Author WT
 * @Date 2020/5/26
 */
public class PlatformFileUtil {

    public PlatformFileUtil() {
    }

    public static void download(String filename, String url) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        String type = (new MimetypesFileTypeMap()).getContentType(filename);
        response.setHeader("Content-type", type);
        String code = new String(filename.getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + code);
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        bis = new BufferedInputStream(new FileInputStream(new File(url)));

        for(int i = bis.read(buff); i != -1; i = bis.read(buff)) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
        }

    }
}
